import Taro from "@tarojs/taro";
import { uploadFileApi } from "./request/request";
import icon_denj_one from "@/assets/image/icon_denj_one.jpg";
import icon_denj_two from "@/assets/image/icon_denj_two.jpg";
import icon_denj_three from "@/assets/image/icon_denj_three.jpg";
import icon_denj_four from "@/assets/image/icon_denj_four.jpg";
import { getGlobalData } from "@/global_data";
import { AddressREG } from "@/constants/common";
import { addCount } from "@/services/entities/all";
/**
 * 对页面地址导航的封装。
 * @param {String} url 页面url地址
 */
export const link = (url) => {
  Taro.navigateTo({
    url,
  }).then();
};

export const back = () => {
  Taro.navigateBack();
};

/**
 * 对页面地址导航的封装。
 * @param {String} url 页面url地址
 */
export const switchTab = (url) => {
  Taro.switchTab({
    url,
  }).then();
};

/**
 * 合并url与参数
 * @param url
 * @param params
 */
export const combineParams = (url: string, params?): string => {
  let str = url;
  if (params && Object.keys(params).length > 0) {
    str += "?";
    for (let i = 0, keys = Object.keys(params); i < keys.length; i += 1) {
      if (i > 0) {
        str += "&";
      }
      str += `${keys[i]}=${params[keys[i]]}`;
    }
  }
  return str;
};

export const getQuery = (url) => {
  // str为？之后的参数部分字符串
  const str = url.substr(url.indexOf("?") + 1);
  // arr每个元素都是完整的参数键值
  const arr = str.split("&");
  // result为存储参数键值的集合
  const result = {};
  for (let i = 0; i < arr.length; i++) {
    // item的两个元素分别为参数名和参数值
    const item = arr[i].split("=");
    result[item[0]] = item[1];
  }
  return result;
};

/**
 * 对页面地址导航的封装。
 * @param {String} url 页面url地址
 * @param params
 */
export const linkWithParams = (url, params?) => {
  console.log(url, params);
  Taro.navigateTo({
    url: combineParams(url, params),
  }).then();
};

/**
 * 对页面地址导航的封装。
 * @param {String} url 页面url地址
 * @param params
 */
export const redirectToWithParams = (url, params?) => {
  Taro.redirectTo({
    url: combineParams(url, params),
  }).then();
};

/**
 * 时间戳格式化
 * @param inputTime
 * @returns {string}
 */
export const formatDateTime = (inputTime: number | string): string => {
  const date = new Date(inputTime);
  const y = date.getFullYear();
  let m: number | string = date.getMonth() + 1;
  m = m < 10 ? `0${m}` : m;
  let d: number | string = date.getDate();
  d = d < 10 ? `0${d}` : d;
  let h: number | string = date.getHours();
  h = h < 10 ? `0${h}` : h;
  let minute: number | string = date.getMinutes();
  let second: number | string = date.getSeconds();
  minute = minute < 10 ? `0${minute}` : minute;
  second = second < 10 ? `0${second}` : second;
  return `${y}/${m}/${d} ${h}:${minute}:${second}`;
};

/**
 * 时间戳格式化
 * @param inputTime
 * @returns {string}
 */
export const formatTime = (inputTime: number | string): string => {
  const date = new Date(inputTime);
  let h: number | string = date.getHours();
  h = h < 10 ? `0${h}` : h;
  let minute: number | string = date.getMinutes();
  let second: number | string = date.getSeconds();
  minute = minute < 10 ? `0${minute}` : minute;
  second = second < 10 ? `0${second}` : second;
  return `${h}:${minute}:${second}`;
};
/**
 * 深拷贝一个对象。考虑引用自身问题,及source检验
 * WeakMap键名为弱引用，且是一个对象
 * @param {Object} source 用于深拷贝的原对象
 * @param wm
 */
export const deepCopy = (source, wm = new WeakMap()) => {
  if (typeof source !== "object" || source === undefined || source === null) {
    return source;
  }

  if (source instanceof Date) {
    return new Date(source);
  }

  if (source instanceof RegExp) {
    return new RegExp(source);
  }

  const result = new source.constructor();
  const vmResult = wm.get(source);
  if (vmResult) {
    return vmResult;
  }

  wm.set(source, result);

  const keys = Object.keys(source);
  keys.forEach((key) => {
    result[key] = deepCopy(source[key], wm);
  });

  return result;
};

/**
 * 对`Taro.showToast`的封装
 * @param title
 * @param {String} type toast icon的类型
 * @param {int} duration toast存在时间
 * @param {Function} onHide toast消失时的回调函数
 */
export const toast = ({ title, duration = 2000, onHide = () => {} }) => {
  if (!title) {
    return;
  }
  setTimeout(() => {
    Taro.showToast({
      title,
      icon: "none",
      duration,
      mask: true,
    }).then(() => {
      if (onHide) {
        setTimeout(() => {
          onHide();
        }, duration);
      }
    });
  }, 300);
};

/**
 * 调用电话api
 */
export const makePhoneCall = (number: string = "400-8576-886") => {
  Taro.makePhoneCall({
    phoneNumber: number,
  }).then();
};

/**
 * 格式化浮点数
 * @param data
 */
export const floatNumber = (data: number | string): string => {
  if (!data) {
    return "0";
  }
  const result = data.toString();
  if (result && result.includes(".") && result.split(".")[1].length > 2) {
    return parseFloat(result.toString()).toFixed(2);
  }
  return parseFloat(result).toString();
};

export const uploadFilesList = async (value: any) => {
  const list = value.map((single) => {
    console.log("single", single);
    if (!single.file && single.url) {
      return { data: single.url };
    }
    return uploadFileApi(single.file?.path);
  });
  return Promise.all(list);
};

export const getLevelName = (level) => {
  switch (Number(level)) {
    case 1:
      return "二级商家";
    case 2:
      return "普通商家";
    case 3:
      return "荣誉商家";
    case 4:
      return "优质商家";
    default:
      return "二级商家";
  }
};

export const getLevelImage = (level) => {
  switch (Number(level)) {
    case 1:
      return icon_denj_four;
    case 2:
      return icon_denj_three;
    case 3:
      return icon_denj_two;
    case 4:
      return icon_denj_one;
    default:
      return icon_denj_four;
  }
};

export const preview = (url, urlList) => {
  Taro.previewImage({ current: url, urls: urlList });
};

export const getUser = () => {
  return getGlobalData("userInfo");
};

export const getImageNumberByLevel = (level) => {
  switch (level) {
    case 4:
      return 80;
    case 3:
      return 20;
    case 2:
    case 1:
      return 6;
    default:
      return 6;
  }
};

export const addressArrConstant = [
  "北京市",
  "天津市",
  "上海市",
  "重庆市",
  "澳门特别行政区",
  "香港特别行政区",
];

export const getAddressArr = (address: string) => {
  let addressArr: any = [];
  const arr = [
    "北京市",
    "天津市",
    "上海市",
    "重庆市",
    "澳门特别行政区",
    "香港特别行政区",
  ];
  if (address) {
    addressArr = address.match(AddressREG);
    if (arr.includes(addressArr[0])) {
      addressArr[1] = addressArr[0];
    }
  }
  return addressArr;
};

export const getAddressArrNew = (address: string[]) => {
  let addressArr: any = [...address];
  const arr = [
    "北京市",
    "天津市",
    "上海市",
    "重庆市",
    "澳门特别行政区",
    "香港特别行政区",
  ];
  if (address) {
    if (arr.includes(addressArr[0])) {
      addressArr[1] = addressArr[0];
    }
  }
  return addressArr;
};

export const saveImage = (imgData: any) => {
  var save = Taro.getFileSystemManager(); // 获取文件管理器对象
  var number = parseInt(Math.random() * 100000);
  save.writeFile({
    filePath: Taro.env.USER_DATA_PATH + "/pic" + number + ".png", // 表示生成一个临时文件名
    data: imgData.replace("data:image/png;base64,", ""),
    encoding: "base64",
    success: (res) => {
      Taro.saveImageToPhotosAlbum({
        filePath: Taro.env.USER_DATA_PATH + "/pic" + number + ".png",
        success: function () {
          Taro.showToast({
            title: "保存成功",
          });
        },
        fail: function (err) {
          console.log(err);
        },
      });
      console.log(res);
    },
    fail: (err) => {
      console.log(err);
    },
  });
};

// 用户未登录则跳转到登陆界面

export const addCounts = (storeId) => {
  const userData = getGlobalData("userInfo");
  addCount({ storeId, type: 1, openId: userData?.openId });
};
